<template>
	<el-drawer
		@closed="closed"
		size="30%"
		v-model="data.drawerShow"
		direction="ltr"
		:title="(data.admins_id !== '' ? `编辑` : `添加`) + `用户`"
		:with-header="true"
	>
		<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px">
			<el-form-item label="用户名" prop="username">
				<el-input v-model="ruleForm.username" />
			</el-form-item>

			<el-form-item label="密码" prop="password" class="elFormItem">
				<el-input
					v-model="ruleForm.password"
					type="password"
					class="input"
					v-show="data.admins_id === '' || (data.admins_id !== '' && data.restPass)"
				/>
				<el-button
					:class="[data.restPass ? 'button' : '']"
					v-show="data.admins_id !== ''"
					type="primary"
					@click="() => restPass(ruleFormRef)"
					>{{ !data.restPass ? `重置密码` : `取消重置` }}</el-button
				>
			</el-form-item>

			<el-form-item label="所属权限" prop="role_id">
				<el-select v-model="ruleForm.role_id" filterable placeholder="请选择所属权限" :loading="data.rolrSelectLoad">
					<el-option v-for="item in data.roleSelect" :key="item.role_id" :label="item.role_name" :value="item.role_id" />
				</el-select>
			</el-form-item>
			<el-form-item label="真实姓名" prop="realName">
				<el-input v-model="ruleForm.realName" />
			</el-form-item>
			<el-form-item label="手机号码" prop="phone">
				<el-input v-model="ruleForm.phone" />
			</el-form-item>
			<el-form-item label="昵称" prop="nickName">
				<el-input v-model="ruleForm.nickName" />
			</el-form-item>
			<el-form-item label="头像" prop="portrait">
				<Upload v-model:value="ruleForm.portrait" v-model:show-value="data.portraitValue" clearable />
			</el-form-item>

			<el-form-item label="状态" prop="status">
				<el-switch
					v-model="ruleForm.status"
					:active-value="1"
					:inactive-value="0"
					:active-text="`启用`"
					:inactive-text="`禁用`"
				/>
			</el-form-item>

			<el-form-item class="save-button">
				<el-button type="primary" @click="() => submitForm(ruleFormRef)">{{ data.admins_id !== '' ? `编辑` : `添加` }}</el-button>
				<el-button @click="() => resetForm()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-drawer>
</template>
<script setup lang="ts" name="PagesFormDrawer">
import { reactive, ref } from "vue";
import type { FormInstance, FormRules, FormItemRule } from "element-plus";

import { ElMessage } from "element-plus";
import { all } from "@/api/modules/role";
import { add, edit } from "@/api/modules/admin";
import { Role } from "@/api/interface/role";
import { checkPhoneNumber } from "@/utils/eleValidate";
import Upload from "@/components/Upload/index.vue";

/* 表单 */
const ruleFormRef = ref<FormInstance>();
interface RuleForm<ROLE_ID = number | undefined, ADMINS_ID = undefined | string> {
	username: string;
	password?: string;
	admins_id: ADMINS_ID;
	nickName: string;
	status: 1 | 0;
	role_id: ROLE_ID;
	portrait: File | string | undefined;
	realName: string;
	phone: string;
	[key: string]: any;
}
const originalForm = (): RuleForm => {
	return {
		username: "",
		password: "",
		nickName: "",
		status: 1,
		phone: "",
		portrait: undefined,
		role_id: undefined,
		admins_id: undefined,
		realName: ""
	};
};
/* 参数 */
const data = reactive<{
	drawerShow: boolean;
	admins_id: string;
	oldForm: RuleForm;
	restPass: boolean;
	roleSelect: Role.All[];
	rolrSelectLoad: boolean;
	color: string;
	portraitValue: string;
}>({
	drawerShow: false,
	restPass: false,
	portraitValue: "",
	admins_id: "",
	oldForm: originalForm(),
	roleSelect: [],
	rolrSelectLoad: false,
	color: document.documentElement.style.getPropertyValue("--el-color-primary") //全局皮肤颜色
});
/*  */

const ruleForm = reactive<RuleForm>(originalForm());
const passRule: Array<FormItemRule> = [
	{ required: true, message: "密码不为空", trigger: "blur" },
	{
		min: 5,
		message: "不能小于5字符",
		trigger: "blur"
	},
	{
		max: 20,
		message: "不能超过20字符",
		trigger: "blur"
	}
];
const rules = reactive<FormRules>({
	username: [
		{ required: true, message: "用户名称不为空", trigger: "blur" },
		{
			min: 5,
			message: "不能小于5字符",
			trigger: "blur"
		},
		{
			max: 20,
			message: "不能超过20字符",
			trigger: "blur"
		}
	],
	nickName: [
		{ required: true, message: "昵称不为空", trigger: "blur" },
		{
			max: 20,
			message: "不能超过20字符",
			trigger: "blur"
		}
	],
	realName: [
		{ required: true, message: "真实姓名不为空", trigger: "blur" },
		{
			max: 20,
			message: "不能超过20字符",
			trigger: "blur"
		}
	],
	role_id: [{ required: true, message: "权限不为空", trigger: "blur" }],
	phone: [
		{ required: true, message: "电话号码", trigger: "blur" },
		{ required: true, validator: checkPhoneNumber, trigger: "blur" }
	]
});

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			if (data.admins_id !== '') {
				let form = ruleForm;
				if(!data.restPass) delete form['password'];
				await edit({ ...form, admins_id: data.admins_id } as RuleForm<number, string>);
				ElMessage.success("编辑成功");
			} else {
				await add(ruleForm as RuleForm<number>);
				ElMessage.success("添加成功");
			}
			data.drawerShow = false;
			emit("close");
		} else {
			console.log("error submit!", fields);
		}
	});
};

const resetForm = () => {
	const original: RuleForm = data.admins_id === '' ? originalForm() : data.oldForm;
	for (let key in original) if (ruleForm.hasOwnProperty(key)) ruleForm[key] = original[key];
};

const loadAll = async () => {
	data.rolrSelectLoad = true;
	let res = await all();
	data.rolrSelectLoad = false;
	data.roleSelect = res.data;
	// data.roleSelect.unshift({
	// 	role_id: 0,
	// 	role_name: "超级管理员(拥有所有权限,不在列表显示)"
	// });
};

/**
 * 关闭弹窗清空表单
 */
const closed = () => {
	const original: RuleForm = originalForm();
	for (let key in original) if (ruleForm.hasOwnProperty(key)) ruleForm[key] = original[key];
	rules.password = passRule;
};

/*  */

/**
 * 对外暴露子组建方法
 */
const open = (params: RuleForm<number, string> | undefined = undefined, portraitValue: string = "") => {
	ruleFormRef.value?.clearValidate();
	if (params !== undefined) {
		data.admins_id = params.admins_id;
		let key: keyof RuleForm;
		for (key in params) {
			if (ruleForm.hasOwnProperty(key)) ruleForm[key] = params[key];
			if (data.oldForm.hasOwnProperty(key)) data.oldForm[key] = params[key];
		}
		data.restPass = false;
	  delete rules.password;
	}else{
		data.admins_id = ''; //添加
		data.restPass = true;
	}
	// data.portraitValue = portraitValue;
	loadAll();
	data.drawerShow = true;
};
defineExpose({
	open
});
/*  */
/**
 * 事件回调
 */
const emit = defineEmits<{
	(event: "close"): void;
}>();
/*  */

const restPass = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	data.restPass = !data.restPass;
	if (data.restPass) {
		rules.password = passRule;
		ruleForm.password = "";
	} else {
		delete rules.password;
	}
	formEl.clearValidate(["password"]);
};
</script>
<style scoped lang="scss">
@import "./index.scss";
.save-button {
	margin-top: 50px;
}
</style>
